package captcha

import (
	"context"
	"gitee.com/hxchjm/go-admin/pkg/db"
	"github.com/mojocn/base64Captcha"
	"github.com/redis/go-redis/v9"
	"time"
)

type cacheStore struct {
	expiration int
	cache      *redis.Client
}

// NewCacheStore returns a new standard memory store for captchas with the
// given collection threshold and expiration time (duration). The returned
// store must be registered with SetCustomStore to replace the default one.
func NewCacheStore(expiration int) base64Captcha.Store {
	s := new(cacheStore)
	s.expiration = expiration
	s.cache = db.GetRedis()
	return s
}

// Set sets the digits for the captcha id.
func (e *cacheStore) Set(id string, value string) error {
	return e.cache.SetEx(context.Background(), id, value, time.Second*time.Duration(e.expiration)).Err()
}

// Get returns stored digits for the captcha id. Clear indicates
// whether the captcha must be deleted from the store.
func (e *cacheStore) Get(id string, clear bool) string {
	res, err := e.cache.Get(context.Background(), id).Result()
	if err == nil {
		if clear {
			_ = e.cache.Del(context.TODO(), id)
		}
		return res
	}
	return ""
}

// Verify captcha's answer directly
func (e *cacheStore) Verify(id, answer string, clear bool) bool {
	return e.Get(id, clear) == answer
}
